import axios from 'axios'
import iView from 'iview'

let router
const isClient = process.env.VUE_ENV === 'client'

const instance = axios.create({
  baseURL: isClient ? '/api' : 'http://localhost:3000/api',
  timeout: 5000
})

instance.interceptors.request.use(config => {
  let token
  if (isClient) {
    token = window.localStorage.getItem('token')
  } else {
    token = ''
  }
  config.headers.Authorization = `Bearer ${token}`
  return config
}, error => Promise.reject(error))

instance.interceptors.response.use(res => {
  const body = res.data
  if (body.code === 0) {
    return body
  } else {
    iView.Notice.error({
      title: 'Error',
      desc: body.msg
    })
    return Promise.reject(res)
  }
}, error => {
  const res = error.response
  if (res) {
    if (res.status === 401) {
      router.push('/login')
    }
  }
})

const createApi = (url, method, config = {}) => {
  return instance({
    url,
    method,
    ...config
  })
}

const initApi = _router => (router = _router)

export {
  initApi,
  createApi
}
